﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using IdentityModel;
using IdentityModel.Client;
using IdentityServer4.Services;
using leapt.Api.ViewModels.User;
using leapt.Common;
using leapt.Common.Tools;
using leapt.Domain.Entities;
using leapt.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace leapt.Api.Controllers
{
    /// <summary>
    /// 用户中心
    /// </summary>
    //[Authorize("Permission")]
    //[Authorize]
    [EnableCors(WebApiOption.CORS_POLICY_NAME)]
    public class AccountController : BaseController
    {
        private readonly IUserService _userService;
        private IConfiguration _config { get; }
        /// <summary>
        /// 自定义策略参数
        /// </summary>
        public AccountController(IUserService userService, IConfiguration configuration)
        {
            this._userService = userService;
            this._config = configuration;
        }
        
        /// <summary>
        /// 提交登陆请求
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("/api/login")]
        public async Task<IActionResult> Login([FromBody] LoginViewModel model)
        {
            if (model == null)
            {
                return BadRequest();
            }
            //如果视图模型中的属性没有验证通过，则返回到登录页面，要求用户重新填写
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            //根据用户登录名查询指定用户实体
            var user = _userService.FindByLoginName(model.UserName.Trim());

            //如果用户不存在，则携带错误消息并返回登录页面
            if (user == null)
            {
                ModelState.AddModelError("message", "用户不存在");
                return NotFound(ModelState);
            }

            //如果密码不匹配，则携带错误消息并返回登录页面
            if (user.Password != Encryptor.Md5Hash(model.Password.Trim()))
            {
                ModelState.AddModelError("message", "密码错误,请重新登录");
                return BadRequest();
            }

            //请求授权服务器
            var diso = DiscoveryClient.GetAsync(_config.GetSection("WebAPI:Auth:AuthorityUrl").Value).Result;
            if (diso.IsError)
            {
                ModelState.AddModelError("message", diso.Error);
                return BadRequest(ModelState);
            }

            //授权服务器根据客户端发来的请求返回令牌
            var tokenClient = new TokenClient(diso.TokenEndpoint, "client_auth_client", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("leapt_auth_api");
            if (tokenResponse.IsError)
            {
                ModelState.AddModelError("message", diso.Error);
                return BadRequest(ModelState);
            }
            //如果成功，则打印输出返回的令牌信息
            else
            {
                Console.WriteLine(tokenResponse.Json);
            }

            return Ok(new { token = tokenResponse.AccessToken });
        }

        /// <summary>
        /// 提出登出请求
        /// </summary>
        /// <returns></returns>
        [HttpPost("/api/logout")]
        public IActionResult Logout()
        {
            return Ok();
        }

        /// <summary>
        /// 提交注册请求
        /// </summary>
        /// <param name="model"></param>
        /// <remarks>
        /// 请求示例:
        ///     POST /api/account/register
        ///     {
        ///         "userName": "test",
        ///         "password": "123",
        ///         "confirmPassword": "123"
        ///     }
        /// </remarks>
        /// <returns></returns>
        /// <returns code="201"></returns>
        /// <returns code="400">model为null</returns>
        [AllowAnonymous]
        [HttpPost("register")]
        [ProducesResponseType(typeof(RegisterViewModel), 201)]
        [ProducesResponseType(typeof(RegisterViewModel), 400)]
        public IActionResult Register([FromBody] RegisterViewModel model)
        {
            if (model == null)
            {
                return BadRequest();
            }

            //创建一个用户实体
            var user = new User
            {
                LoginName = model.UserName,
                Password = Encryptor.Md5Hash(model.Password.Trim()),
                CreatedOn = DateTime.Now,
                Status = 1
            };

            //将用户实体对象写入数据库中
            var ret = _userService.Insert(user);
            if (ret <= 0)
            {
                //如果注册失败,则携带错误消息并返回注册页面
                ModelState.AddModelError("error_message", "注册失败");
                //return View(model);
            }

            return Ok(ret);
        }

       
    }
}
